/*!
 * Dashboard.
 * Date: 2015/07/06.
 * Copyright© 2014-2015 Vamaker All Rights Reserved.
 */
require([
    'jquery',
    'pageInit',
    'amcharts',
    'amcharts.serial'
  ], function ($, vamakerPage) {
  $(function () {
    var $chartDataHolder = $('#advertiser-data'),
      $totalDateOp = $('#total-date-op').find('input'),
      $loadingWrap = $('#content-loading-wrap'),
      appColors = VAM.getVar("VAM_PARAMS").colors,
      filterStatus = VAM.getVar('FILTER_STATUS'),
      units1 = '',
      units2 = '',
      chartDataHolder, chartDataReq, advertiserData,
      langVer = VAM.getVar("LANGUAGE");

      var
      chartGraph = [
        {
          "id": "g1",
          "valueAxis": "v1",
          "lineColor": appColors[0],
          "fillColors": appColors[0],
          "fillAlphas": 1,
          "lineAlpha": 1,
          "type": "column",
          "title": VAM.j('Cost'),
          "valueField": "y0",
          "clustered": false,
          "columnWidth": 0.3,
          "legendValueText": "[[value]]",
          "animationPlayed": true,
          "balloonText": "[[title]]<br/><b style='color: " + appColors[0] + "'>●</b><b> [[value]]</b>"
        },
        {
          "id": "g3",
          "valueAxis": "v1",
          "bullet": "round",
          "bulletBorderAlpha": 1,
          "bulletColor": "#FFFFFF",
          "bulletSize": 6,
          "hideBulletsCount": 50,
          "lineThickness": 2,
          "lineColor": appColors[2],
          "type": "line",
          "title": VAM.j('Click'),
          "useLineColorForBulletBorder": true,
          "valueField": "y2",
          "animationPlayed": true,
          "balloonText": "[[title]]<br/><b style='color: " + appColors[2] + "'>●</b><b> [[value]]</b>"
        },
        {
          "id": "g6",
          "valueAxis": "v4",
          "bullet": "diamond",
          "bulletBorderAlpha": 1,
          "bulletColor": "#FFFFFF",
          "bulletSize": 6,
          "hideBulletsCount": 50,
          "lineThickness": 2,
          "lineColor": appColors[5],
          "type": "line",
          "title": 'CPC',
          "useLineColorForBulletBorder": true,
          "valueField": "y5",
          "animationPlayed": true,
          "balloonText": "[[title]]<br/><b style='color: " + appColors[5] + "'>●</b><b> [[value]]</b>"
        }
      ];

    if (filterStatus) {
      chartGraph.push({
        "id": "g2",
        "valueAxis": "v2",
        "bullet": "square",
        "bulletBorderAlpha": 1,
        "bulletColor": "#FFFFFF",
        "bulletSize": 6,
        "hideBulletsCount": 50,
        "lineThickness": 1,
        "lineColor": appColors[1],
        "type": "line",
        "title": VAM.j('Show'),
        "useLineColorForBulletBorder": true,
        "valueField": "y1",
        "animationPlayed": true,
        "balloonFunction": function (item) {
          return VAM.j('Show') + "<br/><b style='color: " + appColors[1] + "'>●</b><b> " + item["dataContext"]["y1"] + " " + units2 + "</b>";
        }
      });
      chartGraph.push({
        "id": "g4",
        "valueAxis": "v3",
        "bullet": "triangleUp",
        "bulletBorderAlpha": 1,
        "bulletColor": "#FFFFFF",
        "bulletSize": 6,
        "hideBulletsCount": 50,
        "lineThickness": 2,
        "lineColor": appColors[3],
        "type": "line",
        "title": VAM.j('Click Rate'),
        "useLineColorForBulletBorder": true,
        "valueField": "y3",
        "animationPlayed": true,
        "balloonText": "[[title]]<br/><b style='color: " + appColors[3] + "'>●</b><b> [[value]]%</b>"
      });
    }

    chartDataHolder = AmCharts.makeChart("advertiser-data", {
      "type": "serial",
      "fontFamily": '"Helvetica Neue",Helvetica,"Hiragino Sans GB","Segoe UI","Microsoft Yahei",Tahoma,Arial,STHeiti,sans-serif',
      "fontSize": 13,
      "startDuration": 1,
      "creditsPosition": "top-right",
      "dataDateFormat": "YYYY/MM/DD",
      "valueAxes": [{
        "id": "v1",
        "title": VAM.j('Cost') + '(' + VAM.j('￥') + ')' + ' / ' + VAM.j('Click'),
        "position": "left",
        "autoGridCount": true
      }, {
        "id": "v2",
        "title": VAM.j('Show'),
        "gridAlpha": 0,
        "position": "left",
        "autoGridCount": true,
        "labelOffset": 80
      }, {
        "id": "v3",
        "title": VAM.j('Ratio(%)'),
        "gridAlpha": 0,
        "position": "right",
        "autoGridCount": true
      }, {
        "id": "v4",
        "title": 'CPC',
        "gridAlpha": 0,
        "position": "right",
        "autoGridCount": true
        // "labelOffset": 80
      }],
      "graphs": chartGraph,
      "chartCursor": {
        "pan": false,
        "cursorColor": appColors[1],
        "valueLineEnabled": false,
        "valueLineBalloonEnabled": false,
        "cursorAlpha": 0,
        "valueLineAlpha": 0.5
      },
      "categoryField": "x",
      "categoryAxis": {
        "gridAlpha": 0,
        "dashLength": 1,
        "labelRotation": 15,
        "minorGridEnabled": true
      },
      "legend": {
        "useGraphSettings": true,
        "valueAlign": "left",
        "align": "center",
        "valueWidth": 80
      },
      "balloon": {
        "borderThickness": 1,
        "shadowAlpha": 0
      },
      "dataProvider": [{
        x: "-/-",
        y0: 0.00,
        y1: 0,
        y2: 0,
        y3: 0.00,
        y4: 0.00,
        y5: 0.00
      }]
    });
    chartDataHandler = function () {
      var data = advertiserData,
        flag1 = true,
        flag2 = true,
        flag3 = true,
        flag4 = true,
        flag5 = true,
        flag6 = true,
        i = 0, len = data.length;
        myData = [];

      if (langVer === "zh-CN") {
        for (i = 0; i < len; i++){
          // flag1 = flag1 && (data[i].y0 < 10000 ? false : true); //true表都大于1000的
          // flag2 = flag2 && (!flag1 ? false : data[i].y0 < 100000000 ? false : true);//ture表都大于1亿

          flag4 = flag4 && (data[i].y1 < 10000 ? false : true); //true表都大于1000的
          flag5 = flag5 && (!flag4 ? false : data[i].y1 < 100000000 ? false : true);//ture表都大于1亿
        }
        for (i = 0; i < len; i++) {
          var item = data[i],
            newItem = {
              "x": item["x"],
              "y0": item["y0"],
              "y1": item["y1"],
              "y2": item["y2"],
              "y3": item["y3"],
              "y4": item["y4"],
              "y5": item["y5"]
            };


          // if (flag2) {
          //   units1 = ' 亿元';
          //   newItem["y0"] = parseFloat((item["y0"] / 100000000).toFixed(2));
          // } else if (flag1) {
          //   units1 = ' 万元';
          //   newItem["y0"] = parseFloat((item["y0"] / 10000).toFixed(2));
          // } else {
          //   units1 = ' 元';
          //   newItem["y0"] = parseFloat((item["y0"]).toFixed(2));
          // }

          if (flag5) {
            units2 = ' 亿';
            newItem["y1"] = parseFloat((item["y1"] / 100000000).toFixed(2));
          } else if (flag4) {
            units2 = ' 万';
            newItem["y1"] = parseFloat((item["y1"] / 10000).toFixed(2));
          } else {
            units2 = ' ';
            newItem["y1"] = parseFloat((item["y1"]).toFixed(2));
          }
          myData.push(newItem);
        }
      } else {
        for (i = 0; i < len; i++){
          // flag1 = flag1 && (data[i].y0 < 1000 ? false : true); //true表都大于1000的
          // flag2 = flag2 && (!flag1 ? false : data[i].y0 < 1000000 ? false : true);//ture表都大于1百万
          // flag3 = flag3 && (!flag1 ? false : !flag2 ? false : data[i].y0 < 1000000000 ? false : true) //true表都大于十亿

          flag4 = flag4 && (data[i].y1 < 1000 ? false : true); //true表都大于1000的
          flag5 = flag5 && (!flag4 ? false : data[i].y1 < 1000000 ? false : true);//ture表都大于1百万
          flag6 = flag6 && (!flag4 ? false : !flag5 ? false : data[i].y1 < 1000000000 ? false : true) //true表都大于十亿
        }
        for (i = 0; i < len; i++) {
          var item = data[i],
            newItem = {
              "x": item["x"],
              "y0": item["y0"],
              "y1": item["y1"],
              "y2": item["y2"],
              "y3": item["y3"],
              "y4": item["y4"],
              "y5": item["y5"]
            };


          // if (flag3) {
          //   units1 = ' B(￥)';
          //   newItem["y0"] = parseFloat((item["y0"] / 1000000000).toFixed(2));
          // } else if (flag2) {
          //   units1 = ' M(￥)';
          //   newItem["y0"] = parseFloat((item["y0"] / 1000000).toFixed(2));
          // } else if (flag1) {
          //   units1 = ' K(￥)';
          //   newItem["y0"] = parseFloat((item["y0"] / 1000).toFixed(2));
          // } else {
          //   units1 = ' ￥';
          //   newItem["y0"] = parseFloat((item["y0"]).toFixed(2));
          // }

          if (flag6) {
            units2 = ' B';
            newItem["y1"] = parseFloat((item["y1"] / 1000000000).toFixed(2));
          } else if (flag5) {
            units2 = ' M';
            newItem["y1"] = parseFloat((item["y1"] / 1000000).toFixed(2));
          } else if (flag4) {
            units2 = ' K';
            newItem["y1"] = parseFloat((item["y1"] / 1000).toFixed(2));
          } else {
            units2 = ' ';
            newItem["y1"] = parseFloat((item["y1"]).toFixed(2));
          }
          myData.push(newItem);
        }
      }

      chartDataHolder.dataProvider = myData;
      chartDataHolder.validateNow();
      chartDataHolder.validateData();
    };
    chartDataReq = function (date) {
      $.ajax({
        url: VAM.getVar('DATA_LIST_URL'),
        type: 'GET',
        dataType: 'json',
        data: {
          type: date,
          rnd: (new Date()).getTime()
        },
        beforeSend: function(){
          $loadingWrap.show();
        }
      })
      .done(function (data) {
        // console.log(data);
        advertiserData = data['graph'];
        chartDataHandler();

        // chartDataHolder.dataProvider = advertiserData;
        // chartDataHolder.validateNow();
        // chartDataHolder.validateData();
      })
      .fail(function() {
        console.log("error");
      })
      .always(function() {
        $loadingWrap.fadeOut();
      });
    };

    // 日/月/年图表操作
    $totalDateOp.on('change', function(evt) {
      var $me = $(this),
        type = $me.val();
      chartDataReq(type)
    });

    chartDataReq('day');
  });
});
